from math import sin, cos, atan2, sqrt,  pi

def MeanAnomaly(t, P):
    if abs(t - P) < 0.1:
        return 0
    return 360*t/P

def EccentricAnomaly(M, e):
    M = M*pi/180.0
    a = 0
    for i in range(5):
        b = a
        a = a + (M + e*sin(a) - a)/(1 - e*cos(a))
        if abs(a - b) < 0.2:
            break
    return a

def TrueAnomaly(t, P, e):
    x = EccentricAnomaly(MeanAnomaly(t, P), e)
    theta = atan2(sqrt(1.0 - e**2)*sin(x), cos(x) - e)*180.0/pi
    if theta < 0:
        theta += 360
        if theta == 360.0:
            return 0.0
    return theta

def Distance(a, theta, e, phi=0):
    theta = theta*pi/180.0
    return a*(1 - e**2)/(1 + e*cos(theta - phi))

constant = 2.97472505e-19

if __name__ == "__main__":
    P = 20
    a = (P**2/constant)**(1.0/3.0)
    print a
    e = .01

    for t in range(-10, 10):
        theta = TrueAnomaly(t, P, e)
        r = Distance(a, theta, e)
        print int(r), "|", int(theta)
